<template>
     <el-form :inline="true" :model="form" label-width="auto" style="padding: 10px;">
        <el-form-item label="编码">
                  <el-input v-model="form.code" :disabled="action!='add'"/>
                </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="form.name"/>
        </el-form-item>
       <el-form-item label="类别">
         <el-input v-model="form.category"/>
       </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark"  style="width: 700px;"/>
        </el-form-item>

       <el-tabs v-model="activeName" class="demo-tabs">
         <el-tab-pane label="遥测信号" name="first">
           <el-container>
             <el-aside width="200px" direction="vertical" style="border-right: 1px #ccc solid;">
               <slot name="default">
                   <el-row>
                     <el-col :span="18">
                       <span style="font-size: 16px">遥测信号</span>
                     </el-col>
                     <el-col :span="6">
                       <el-link icon="Plus" type="primary" plain  @click="onSelectSignal()"></el-link>&nbsp;
                       <el-link icon="Minus" type="danger" plain  @click="handleRemoveSignal()"></el-link>
                     </el-col>
                   </el-row>
               </slot>
               <el-table ref="signalListRef"
                         :data="form.signalList"
                         :show-header="false"
                         highlight-current-row
                         :empty-text="'没有数据'"
                         :stripe="false"
                         :row-key="'code'"
                         :current-row-key="currentRow.code"
                         @current-change="handleCurrentChange">
                 <el-table-column prop="code" label="Date"/>
                 <el-table-column prop="name" label="Name"/>
               </el-table>
             </el-aside>
             <el-main>
                 <el-form :model="currentRow" label-width="100px" :inline="true" style="padding: 10px;">
                   <el-form-item label="编码">
                     <el-input v-model="currentRow.code" :disabled="action!='add'"/>
                   </el-form-item>
                   <el-form-item label="名称">
                     <el-input v-model="currentRow.name"/>
                   </el-form-item>
                   <el-form-item label="类别">
                     <el-input v-model="currentRow.category"/>
                   </el-form-item>
                   <el-form-item label="单位">
                     <el-input v-model="currentRow.unit"/>
                   </el-form-item>
                   <el-form-item label="数据类型">
                     <el-select v-model="currentRow.fieldType" placeholder="请选择活动区域" size>
                       <el-option v-for="item in dict.fluxData" :label="item.label" :value="item.value" :key="item.value"/>
                     </el-select>
                   </el-form-item>
                   <el-form-item label="默认值">
                     <el-input v-model="currentRow.defaultValue"/>
                   </el-form-item>
                   <el-form-item label="存储策略">
                     <el-select v-model="currentRow.storePolicy" placeholder="存储策略">
                       <el-option  v-for="item in dict.storePolicy" :label="item.label" :value="item.value" :key="item.value"/>
                     </el-select>
                   </el-form-item>
                   <el-form-item label="存储间隔" v-if="currentRow.storePolicy==='PERIOD' || currentRow.storePolicy==='PER_CH'">
                     <el-input v-model="currentRow.storeInterval"/>
                   </el-form-item>
                   <el-form-item label="变化类型" v-if="currentRow.storePolicy==='CHANGE' || currentRow.storePolicy==='PER_CH'">
                     <el-select v-model="currentRow.changeType" placeholder="变化类型">
                       <el-option v-for="item in dict.change" :label="item.label" :value="item.value" :key="item.value"/>
                     </el-select>
                   </el-form-item>
                   <el-form-item label="变化值" v-if="currentRow.storePolicy==='CHANGE' || currentRow.storePolicy==='PER_CH'">
                     <el-input v-model="currentRow.changeValue"/>
                   </el-form-item>
                 </el-form>
             </el-main>
           </el-container>
         </el-tab-pane>
         <el-tab-pane label="联动" name="second">
           <el-table :data="sceneList"
                     highlight-current-row
                     :empty-text="'没有数据'"
                     :stripe="false"
                     :row-key="row => row.id"
                     @current-change="handleSceneChange">
             <el-table-column prop="name" label="名称" />
             <el-table-column prop="remark" label="备注" />
             <el-table-column prop="triggerExpress" label="触发表达式"/>
             <el-table-column prop="triggerExpress" label="联动">
               <template v-slot="scope">
                 <div style="white-space: pre-wrap;">
                   {{scope.row.alarmEnable?'告警;':''}}
                   <template v-if="scope.row.actionEnable">
                     <template v-for="(actionFlow,fi) in scope.row.actionFlow" :key="fi">
                       <template v-for="(action,ai) in actionFlow.actions">
                         {{action.name}}{{ai===actionFlow.actions.length-1?'':"➩"}}
                       </template>
                       {{fi===scope.row.actionFlow.length-1?'':';'}}
                     </template>
                   </template>
                 </div>
               </template>
             </el-table-column>
             <el-table-column align="center" label="状态">
               <template v-slot="scope">
                 <el-button v-if="scope.row.status" link type="success" @click="handleChangeStatusScene(scope.row)">启用</el-button>
                 <el-button v-else link type="danger" @click="handleChangeStatusScene(scope.row)">禁用</el-button>
               </template>
             </el-table-column>
             <el-table-column label="操作" align="center">
               <template #default="scope">
                 <el-button link type="primary" @click="handleEditScene(scope.row)">编辑</el-button>
                 <el-button link type="primary" @click="handleRemoveScene(scope.row)">删除</el-button>
               </template>
             </el-table-column>
           </el-table>
           <div style="text-align: center; padding: 10px;">
             <el-button link style="color:#409EFF" @click="handleAddScene">
               <el-icon :size="20">
                 <Plus />
               </el-icon>
             </el-button>
           </div>
           <div style="height: 20px;"></div>
         </el-tab-pane>
       </el-tabs>
          <div style="text-align:center;margin: 10px auto;">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
      </el-form>
  <dwin ref="dialog" :width="860" :url="'/view/signal/select.vue'" :title="'选择'" @onclose="handleClose1"></dwin>
  <dwin ref="sceneDialog" :width="860" :url="'/view/scene/edit.vue'" :title="'新增/编辑场景联动'" @onclose="handleCloseScene"></dwin>
</template>
<script>
    import{reactive, ref} from 'vue'
    import {add,edit} from '/http/profile.js'
    import Dwin from "../../component/dwin.vue";
    import {useDict,tranTable,tranDict} from '/http/options.js'
    import WeekPlan from "../../component/weekPlan.vue";
    const {ElMessage,ElMessageBox} = ElementPlus;
    import SenceEdit from "../scene/edit.vue";
    import {listForExec,remove as removeScene,changeStatus as changeStatusScene,listByProfileCode} from '/http/scene.js'
    export default {
      components: {Dwin,WeekPlan,SenceEdit},
        props:{
          initParams:Object
        },
        setup(props,context){
          const dict = ref({});
          useDict(dict,'fluxData,storePolicy,alarmPolicy,sceneAction,sceneTrigger,change');
            const form=reactive({
              code:'',
              name:'',
              category:'',
              remark:'',
              signalList:[]
            })
          const signalListRef = ref(null);
          const currentRow =ref({
            code:'',
            name:'',
            fieldType:'DOUBLE',
            defaultValue:'',
            category:'',
            unit:'',
            storePolicy:'ALWAYS',
            storeInterval:0,
            changeType:'ANY',
            changeValue:0
          });
          const handleAdd = ()=>{
              if(action.value=='add'){
                add(form).then(res=> {
                  response(res,context)
                });
              }else{
                edit(form).then(res=> {
                  response(res,context)
                });
              }
          }


          const handleCancel = ()=>{
              context.emit('close',false)
          }
          const action = ref('edit');
          const dialog = ref(null);


          const handleClose1 = (data)=>{
            data.forEach(item=>{
              form.signalList.push(item);
            })
            selectFirstRow();

          }

          function selectFirstRow(){
            console.log(form.signalList)
            if(form.signalList&&form.signalList.length>0){
              currentRow.value = form.signalList[0];
            }
          }

          function onSelectSignal(){
            dialog.value.open(form.signalList);
          }


          onMounted(()=>{
            if(props.initParams){
              Object.assign(form,props.initParams)
              action.value= 'edit'
              selectFirstRow();
              loadScene()
            }else{
              action.value= 'add'
            }
          })

          const handleCurrentChange = (val) => {
            console.log(val)
            currentRow.value = val
          }

          const handleRemoveSignal = ()=>{
            const index = form.signalList.findIndex(item=>item.code === currentRow.value.code)
            if(index>=0){
              form.signalList.splice(index,1);
              if(index>form.signalList.length-1){
                currentRow.value = form.signalList[form.signalList.length-1];
              }else{
                currentRow.value = form.signalList[index];
              }
            }
          }

          //---------------------------------------
          //获取联动
          const sceneDialog = ref(null);
          const activeName = ref('first')
          const sceneList = ref([]);
          const loadScene =()=>{
            listByProfileCode(form.code).then(res=>{
              const data = ref(res.data);
              tranTable(data.value,{terminalCode:'terminal',profileCode:'profile'});
              tranDict(data.value,{triggerType:'sceneTrigger'},dict.value)
              sceneList.value = data.value;

            })
          }
          //新增联动
          const handleAddScene =()=>{
            const data = {
              id:'',
              name:'未命名场景',
              remark:'',
              triggerType:'TERMINAL',
              triggerExpress:'',
              profileCode:form.code,
              terminalCode:'',
              signal:'',
              actionEnable:false,
              alarmEnable:false,
              planEnable:false,
              plan:[],
              alarmSetting:{
                triggerMode:'CONTINUOS',
                triggerValue:1,
                detail:'',
                autoClear:false,
                clearMode:'CONTINUOS',
                clearValue:1
              },
              actionFlow:[{actions:[{
                  name:'执行1',
                  actionType:'',
                  profileCode:'',
                  terminalCode:'',
                  delay:0,
                  params:''
                }]}]
            }
            data.openByBusiness = true;
            sceneDialog.value.open(data);
          }
          const handleEditScene =(row)=> {
            row.openByBusiness = true;
            sceneDialog.value.open(row);
          }



          //删除联动
          const handleRemoveScene =(row)=>{
            let rows = ref([row]);
            beforeRemove(rows,()=>{
              removeScene(rows.value.map((item) => item.id).join()).then(res=>{
                if(response(res)){
                  loadScene()
                }
              })
            });
          }

          const handleChangeStatusScene=(row)=>{
            changeStatusScene(row.id,!row.status).then(res=>{
              loadScene()
            })
          }


          //关闭对话框，刷新
          const handleCloseScene=()=>{
            loadScene()
          }


          return{
            form,handleAdd,handleCancel,action,dialog,onSelectSignal,handleClose1,
            dict,currentRow,handleCurrentChange,handleRemoveSignal
            ,sceneList,handleAddScene,handleRemoveScene
            ,handleChangeStatusScene,handleEditScene,handleCloseScene,activeName,sceneDialog
          }
        }
    }
</script>

<style scoped>
.el-form .el-select {
  width: 192px; /* 或者根据需要设置其他宽度 */
}
.vertical-radio .el-radio {
  display: block;
  margin-bottom: 10px; /* 可根据需要调整间距 */
}
.header {
  font-size: 16px;
  border-top: #f0f0f0 solid 1px;
  margin: 0;
  box-shadow: 2px 2px 4px rgba(0,0,0,0.1);
}
</style>